<?php
/**
 * @project kkzc
 * @date 2015-7-3
 * @author xialei <xialeistudio@gmail.com>
 */

namespace app\controllers;

use app\components\CommonTool;
use app\models\User;
use QRcode;
use yii\base\Exception;
use yii\web\Controller;
use yii\web\Response;

class OauthController extends Controller
{
    public $layout = 'mobile';

    /**
     * 生成二维码
     */
    public function actionQrcode()
    {
        $loginKey = md5(\Yii::$app->session->id);
        \Yii::$app->session->set('loginKey', $loginKey);
        $url = \Yii::$app->urlManager->createAbsoluteUrl(['oauth/weblogin', 'key' => $loginKey]);
        require __DIR__ . '/../extensions/phpqrcode/phpqrcode.php';
        \Yii::$app->response->format = Response::FORMAT_RAW;
        QRcode::png($url, false, QR_ECLEVEL_M, 4);
    }

    /**
     * 登录
     * @param $callback
     */
    public function actionLogin($callback)
    {
        $return = \Yii::$app->urlManager->createAbsoluteUrl(['oauth/callback', 'a' => 1]);
        \Yii::$app->session->setFlash('return', $callback);
//        $this->redirect($url);

        $redirect = 'http://abbottwechatf.chinacloudsites.cn/wechat/auth?redirect=' . urlencode($return);
        $this->redirect($redirect);
    }

    /**
     * 回调地址
     * @param string $openid
     * @param int $unixtime
     * @param string $token
     * @return string
     * @internal param null $code
     */
    public function actionCallback($openid = '', $unixtime = 0, $token = '')
    {
        try {

            if (empty($openid) || $unixtime == 0 || empty($token)) {
                throw new Exception('授权失败，请重试');
            }
            $return = \Yii::$app->session->getFlash('return');
            // 获取用户信息
//            $accessToken = \Yii::$app->wechat->getOauth2AccessToken($code);
//            // 检测用户是否存在
            $user = User::findIdentity($openid);
            if (empty($user)) {
                $userInfo = \Yii::$app->wechat->getOauth2ProxyUserInfo($openid, $unixtime, $token);
                $user = new User();
                $user->setAttributes([
                    'openid' => $openid,
                    'nickname' => empty($userInfo['nickname'])?'微信用户':$userInfo['nickname'],
                    'sex' => $userInfo['sex'],
                    'province' => $userInfo['province'],
                    'city' => $userInfo['city'],
                    'country' => $userInfo['country'],
                    'avatar' => $userInfo['headimgurl'],
                    'subscribed' => empty($userInfo['Subscribe']) ? 0 : 1
                ]);
                if (!$user->save()) {
                    throw new Exception('授权失败，请重试');
                }
            }
            \Yii::$app->user->login($user, 7 * 24 * 3600);
            $this->redirect(empty($return) ? '/' : $return);
        } catch (Exception $e) {
            $this->layout = 'mobile';
            return $this->render('error', [
                'message' => $e->getMessage()
            ]);
        }
    }

    /**
     * 显示确认登录浮层
     * @param $key
     * @return string
     */
    public function actionWeblogin($key)
    {
        if (\Yii::$app->user->isGuest) {
            $url = \Yii::$app->urlManager->createUrl(['oauth/login', 'callback' => \Yii::$app->urlManager->createUrl(['oauth/weblogin', 'key' => $key])]);
            \Yii::$app->response->redirect($url);
        }

        // 在手机上显示确认登录浮层
        $this->layout = 'mobile';
        /** @var User $identity */
        $identity = \Yii::$app->user->identity;
        $this->layout = 'mobile';
        return $this->render('weblogin', [
            'user' => $identity->attributes,
            'key' => $key
        ]);
    }

    public function actionAlogin($id)
    {
        $user = User::findIdentity($id);
        \Yii::$app->user->login($user, 7 * 24 * 3600);
    }

    /**
     * 轮询
     */
    public function actionQuery()
    {
        $loginKey = \Yii::$app->session->get('loginKey');
        $cache = \Yii::$app->cache->get($loginKey);
        if (!empty($cache)) {
            /** @var User $user */
            $user = User::findIdentity($cache);
            if(empty($user)){
                CommonTool::json([
                    'status' => 0
                ]);
            }
            \Yii::$app->user->login($user, 7 * 24 * 3600);
            \Yii::$app->cache->delete($loginKey);
            CommonTool::json([
                'status' => 1,
                'data' => $user->attributes
            ]);
        } else {
            CommonTool::json([
                'status' => 0
            ]);
        }
    }

    /**
     * 登录成功
     * @param $key
     * @return string
     */
    public function actionSuccess($key)
    {
        if (\Yii::$app->user->isGuest) {
            $url = \Yii::$app->urlManager->createUrl(['oauth/login', 'return' => \Yii::$app->urlManager->createUrl(['oauth/weblogin', 'key' => $key])]);
            \Yii::$app->response->redirect($url);
        }
        \Yii::$app->cache->set($key, \Yii::$app->user->id);
        $this->layout = 'absolute';
        return $this->render('success');
    }

    public function actionLogout()
    {
        \Yii::$app->user->logout();
        $this->redirect(['/']);
    }
}